(function (G) {
    G.Storage.init('isZhiNeng', 1)
    G.vue({
        data: {
            inventoryList: null, // 范围内的资源点
            sampleType: null, // 类型
            sampleNums: null, // 数量
            sampleScope: null, // 范围
            isZhiNeng: 0, // 是否是智能推荐的点，0不是1是 智能生成检查点
            userId1: null,
            caseId: null,
            koufenId: null,
            inventoryId: null, // 保存所有当日任务
            recordList: [], // 保存所有当日任务
            index: null, // 最近的点是第几个
            units: [], // 保存所有附近机构
            unit: [], // 当前选中的资源、机构
            juli: 1000, // 设置打卡范围单位米
            minJuli: 10000, // 最近的距离
            timeController: false, // 定时器
            unitId: '', // 最近的单位id
            unitName: '', // 最近的单位名
            name: '', // 最近资源名
            nameList: '', // 可以选的所有资源名
            type: '', // 资源类型
            patroltype: '1', // 巡查类型
            unitUser: null, // 最近的单位负责人id
            markers: [], // 所有标记点
            currenMarker: [], // 自己位置的marker
            othermarkers: [], // 不包含当前位置的标记点
            address: '', // 当前地址
            latitude: '', // 当前纬度
            longitude: '', // 当前经度
            currentTime: '', // 页面显示当前时间
            locationIcon: G.Storage.get('APIURL') + '/file/1593488692939460608',
            calendaUrl: G.Storage.get('APIURL') + '/file/1589179512531324928',
            refreshUrl: G.Storage.get('APIURL') + '/file/1596412684021141504',
            uploadImg: ''
        },
        methods: {
            // 点击标记点，返回标记点id
            markerInfo(e) {
                console.log('--edetail', e.detail);
            },
            // 点击地图获取经纬度
            getLocat(e) {
                console.log('--e', e.detail.latitude);
                console.log('--e', e.detail.longitude);
            },
            toSafeCase() {
                G.$go(`/pages/safetyTraining/case/index?address=${this.data.address}&longitude=${this.data.longitude}&latitude=${this.data.latitude}`)
            },
            toAddCase() {
                let that = this
                if(this.data.adding){
                    return false
                }
                this.data.adding = true
                G.postWeRun().then(res => {
                    this.data.adding = false
                    if(res.errorMsg){
                        return
                    }
                    let param = {}
                    param.userId = G.Storage.get('userInfo').id
                    let time1 = new Date()
                    param.patrolDate = that.formatDate1(time1)
                    param.latitude = that.data.latitude
                    param.longitude = that.data.longitude
                    param.local = that.data.address
                    param.unit = that.data.unit
                    param.inventoryId = that.data.inventoryId
                    let type = that.data.patroltype
                    if (false) {
                    // if (type == 1) {
                        wx.navigateTo({
                            url: '/pages/check/write/index?type=' + type
                        })
                    } else {
                        wx.navigateTo({
                            url: '/pages/gycase/addAndKoufen/index?type=' + type + '&param=' + JSON.stringify(param),
                            events: {
                                addRecord: function (data) {
                                    console.log('--data', data);
                                    that.setData({
                                        koufenId: data.koufenId,
                                        caseId: data.caseId
                                    })
    
                                    // G.get(G.Storage.get('JAVAURL') + '/sample/addWeight', {
                                    //     id: that.data.inventoryId,
                                    //     weight: 2
                                    // }).then(res => {
                                    //     console.log('--res', res);
                                    // })
                                    that.daka(3)
                                    wx.navigateBack()
                                }
                            },
                        })
                    }
                })
            },
            // 点击异常打卡
            toAddCase1() {
                let that = this
                let units = that.data.units
                // if (units.length == 0) {
                //     console.log('--units1', units);
                //     // wx.showToast({
                //     //     title: '不在管理范围内',
                //     //     icon: 'error',
                //     // })
                // } else {
                let param = {}
                param.userId = G.Storage.get('userInfo').id
                let time1 = new Date()
                param.patrolDate = that.formatDate1(time1)
                param.latitude = that.data.latitude
                param.longitude = that.data.longitude
                param.local = that.data.address
                param.unit = that.data.unit
                param.inventoryId = that.data.inventoryId
                wx.showActionSheet({
                    itemList: ['立案', '扣分', '立案并扣分'],
                    success: function (res) {
                        if (res.tapIndex == 0) {
                            wx.navigateTo({
                                url: '/pages/gycase/add/index?param=' + JSON.stringify(param),
                                events: {
                                    someEvent: function (data) {
                                        console.log('--data', data);
                                        that.setData({
                                            caseId: data.id
                                        })
                                        G.get(G.Storage.get('JAVAURL') + '/sample/addWeight', {
                                            id: that.data.inventoryId,
                                            weight: 2
                                        }).then(res => {
                                            console.log('--res', res);
                                        })
                                        that.daka(3)
                                        wx.navigateBack()
                                    }
                                },
                            })
                        }
                        if (res.tapIndex == 1) {

                            wx.navigateTo({
                                url: '/pages/check/write/index?type=' + that.data.patroltype,
                                events: {
                                    addRecord: function (data) {
                                        console.log('--data', data);
                                        that.setData({
                                            koufenId: data.id
                                        })
                                        that.daka(3)
                                        wx.navigateBack()
                                    }
                                },
                            })


                            // wx.showActionSheet({
                            //     itemList: ['日常巡查', '月度考核', '公众监督', '重大事件'],
                            //     success: function (res) {
                            //         let patroltype
                            //         if (res.tapIndex == 0) {
                            //             patroltype = '1'
                            //         }
                            //         if (res.tapIndex == 1) {
                            //             patroltype = '2'
                            //         }
                            //         if (res.tapIndex == 2) {
                            //             patroltype = '3'
                            //         }
                            //         if (res.tapIndex == 3) {
                            //             patroltype = '4'
                            //         }
                            //         wx.navigateTo({
                            //             url: '/pages/check/write/index?type=' + parseInt(patroltype),
                            //             events: {
                            //                 addRecord: function (data) {
                            //                     console.log('--data', data);
                            //                     that.setData({
                            //                         koufenId: data.id
                            //                     })
                            //                     that.daka(3)
                            //                 }
                            //             },
                            //         })
                            //     }
                            // })
                        }
                        if (res.tapIndex == 2) {
                            wx.navigateTo({
                                url: '/pages/gycase/addAndKoufen/index?type=' + that.data.patroltype + '&param=' + JSON.stringify(param),
                                events: {
                                    addRecord: function (data) {
                                        console.log('--data', data);
                                        that.setData({
                                            koufenId: data.koufenId,
                                            caseId: data.caseId
                                        })
                                        that.daka(3)
                                        wx.navigateBack()
                                    }
                                },
                            })


                            // wx.showActionSheet({
                            //     itemList: ['日常巡查', '月度考核', '公众监督', '重大事件'],
                            //     success: function (res) {
                            //         let patroltype
                            //         if (res.tapIndex == 0) {
                            //             patroltype = '1'
                            //         }
                            //         if (res.tapIndex == 1) {
                            //             patroltype = '2'
                            //         }
                            //         if (res.tapIndex == 2) {
                            //             patroltype = '3'
                            //         }
                            //         if (res.tapIndex == 3) {
                            //             patroltype = '4'
                            //         }
                            //         console.log('---patroltype', patroltype);
                            //         wx.navigateTo({
                            //             url: '/pages/gycase/addAndKoufen/index?type=' + parseInt(patroltype) + '&param=' + JSON.stringify(param),
                            //             events: {
                            //                 addRecord: function (data) {
                            //                     console.log('--data', data);
                            //                     that.setData({
                            //                         koufenId: data.koufenId,
                            //                         caseId: data.caseId
                            //                     })
                            //                     that.daka(3)
                            //                 }
                            //             },
                            //         })
                            //     }
                            // })
                        }
                    }
                })
                // }
            },
            // 跳转到日历页面
            toCalenda() {
                wx.navigateTo({
                    url: '/pages/gypatrol/Calendar/index?patroltype=' + this.data.patroltype,
                })
            },
            // 获取当前定位，并在地图上标点，设为中心点
            getlocal() {
                // wx.showLoading({
                //     title: '加载中',
                // })
                let that = this
                console.log('userinfo', G.Storage.get('userInfo'));
                that.setData({
                    userId1: G.Storage.get('userInfo').userName
                })
                wx.getLocation({
                    type: 'gcj02', //返回可以用于 wx.openLocation 的经纬度
                    success(res) {
                        //真实获取经纬度
                        const latitude = res.latitude
                        const longitude = res.longitude
                        // let param = []
                        // param.push({
                        //     'callout': {
                        //         'content': 'adfsad',
                        //         'color': 'red'
                        //     },
                        //     latitude,
                        //     longitude,
                        //     'iconPath': G.Storage.get('APIURL') + '/file/1596477426853089280',
                        //     'id': 0,
                        //     'width': '30',
                        //     'height': '30'
                        // })
                        // console.log('--markers1', param, latitude, longitude);
                        // that.setData({
                        //     latitude: latitude,
                        //     longitude: longitude,
                        //     markers: param
                        // })
                        //写死当前经纬度
                        let params = []
                        params.push({
                            // latitude: '29.517626733864798', // 范围外
                            // longitude: '106.55703756172807',
                            latitude, // 任务内
                            longitude,
                            // latitude: '29.524958996301713', // 任务外
                            // longitude: '106.49222838253843',
                            width: '30',
                            height: '30',
                            'iconPath': G.Storage.get('APIURL') + '/file/1596477426853089280',
                        })
                        that.setData({
                            // latitude: '29.517626733864798', // 范围外
                            // longitude: '106.55703756172807',
                            latitude, // 任务内
                            longitude,
                            // latitude: '29.524958996301713', // 任务外
                            // longitude: '106.49222838253843',
                            markers: params,
                            currenMarker: params
                        })
                        //结束
                        // that.getRandomPatrol()
                        console.log('--to getLoctionInfo');
                        that.getLoctionInfo()
                    },
                    fail(e) {
                        console.log('--e', e);
                    }
                })
            },
            // 传入经纬度获取该点信息
            getLoctionInfo() {
                G.get('/v1/map/geocodeRegeo', {
                    longitude: this.data.longitude,
                    latitude: this.data.latitude
                }).then(res => {
                    this.setData({
                        address: res.regeocode.formatted_address
                    })
                    this.getPatrolTask()
                })
            },
            // getLocationInfo_back1() {
            //     let that = this
            //     G.get('/v1/map/getLoctionInfo', {
            //         longitude: that.data.longitude,
            //         latitude: that.data.latitude
            //     }).then(res => {
            //         console.log('a--a',res);
            //         if (res.length == 0) {
            //             wx.hideLoading()
            //             console.log('res1--', res);
            //             wx.showToast({
            //                 title: '不在管理范围内',
            //             })
            //         } else {
            //             console.log('--a1', res[0].type);
            //             let list = []
            //             res.forEach(ret => {
            //                 list.push(ret.name)
            //             })
            //             that.setData({
            //                 address: res[0].address,
            //                 units: res,
            //                 unit: res[0],
            //                 inventoryId: res[0].id ? res[0].id : null,
            //                 unitName: res[0].unitName,
            //                 name: res[0].name,
            //                 nameList: list,
            //                 nameIndex: '',
            //                 type: res[0].type,
            //                 unitUser: res[0].userId,
            //                 unitId: res[0].unitId,
            //             })
            //             console.log('--以获取地址，to getPatrolTask');
            //             that.getPatrolTask()
            //         }
            //     })
            // },
            // 获取自己当天的任务
            getPatrolTask() {
                let that = this
                let time1 = new Date()
                let crt = that.formatDate2(time1).toString()
                console.log('--patroltype', that.data);
                G.get('/v1/currentPartrolTask/list', {
                    userId: G.Storage.get('userInfo').id,
                    patrolDate: that.formatDate1(time1),
                    crt: crt,
                    patroltype: that.data.patroltype,
                    taskId: 'IS NOT NULL',
                    // })
                    // G.get('/api/model/g_patrol_record', {
                    //     userId: G.Storage.get('userInfo').id,
                    //     patrolDate: that.formatDate1(time1),
                    // startTime: {$lte:crt},
                    // // endTime: {$nte:crt},
                    //     taskId: 'IS NOT NULL',
                }).then(res => {
                    if (!res.errorMsg) {
                        console.log('---currentPartrolTask', res);
                        if (res.length == 0) { //是否开启智能推荐
                            let timea = new Date()
                            // if (false) {
                            let isZhiNeng = G.Storage.get('isZhiNeng')
                            if (that.formatDate1(timea) != (isZhiNeng ? isZhiNeng.time : '0')) { //今天没有开启过智能推荐
                                // G.confirm('今日无巡查点要求，启用智能推荐巡查点？').then(res => {
                                //     that.getZhineng()
                                // })
                            } else {
                                let isZhiNeng = G.Storage.get('isZhiNeng') || {}
                                that.setData({
                                    recordList: isZhiNeng.recordList || [], // 所有任务记录
                                    othermarkers: isZhiNeng.othermarkers || [], // 除了当前定位以外的其他点
                                    markers: isZhiNeng.markers || [], // 所有点
                                    isZhiNeng: 1,
                                })
                                that.getInstance()
                            }
                        } else {
                            let list = []
                            for (let i = 0; i < res.length; i++) {
                                let paramJson = {
                                    latitude: res[i].latitude,
                                    longitude: res[i].longitude,
                                    iconPath: res[i].statu == 1 ? G.Storage.get('APIURL') + '/file/1596477445610016768' : res[i].statu == 2 ? G.Storage.get('APIURL') + '/file/1596477457052078080' : G.Storage.get('APIURL') + '/file/1596477436479016960',
                                    width: '30',
                                    height: '30',
                                }
                                list.push(paramJson)
                            }
                            let list1 = []
                            list1.push(...list)
                            list1.push(...that.data.currenMarker)
                            that.setData({
                                recordList: res, // 所有任务记录
                                othermarkers: list, // 除了当前定位以外的其他点
                                markers: list1 // 所有点
                            })
                            console.log('--markers2', list1);
                            if (res.length > 0) {
                                let nn = 0
                                res.forEach(i => {
                                    if (i.statu == '1') {
                                        nn++
                                    }
                                })
                                console.log('---nn', nn);
                                if (nn == 0) {
                                    console.log('---res.taskId', res);
                                    G.put('/api/model/g_patrol_task', {
                                        id: res[0].taskId,
                                        statu: 2,
                                        isOnline: 1,
                                    })
                                }
                            }
                            that.getInstance()
                        }
                    }
                })
            },
            getZhineng() {
                let that = this
                let list = []
                G.post(G.Storage.get('JAVAURL') + '/sample/getSampleNear?longitude=' + that.data.longitude + '&latitude=' + that.data.latitude).then(res => {
                    if (!res.errorMsg) {
                        console.log('---res.data', res.data);
                        for (let i = 0; i < res.data.length; i++) {
                            let paramJson = {
                                latitude: res.data[i].location[1],
                                longitude: res.data[i].location[0],
                                iconPath: G.Storage.get('APIURL') + '/file/1596477445610016768',
                                width: '30',
                                height: '30',
                            }
                            list.push(paramJson)
                        }
                        let list1 = []
                        list1.push(...list)
                        list1.push(...that.data.currenMarker)
                        that.setData({
                            recordList: res.data, // 所有任务记录
                            othermarkers: list, // 除了当前定位以外的其他点
                            markers: list1, // 所有点
                            isZhiNeng: 1,
                        })
                        console.log('--recordList1', that.data.recordList);
                        console.log('--markers4', that.data.markers);
                        let time1 = new Date();
                        G.Storage.set('isZhiNeng', {
                            recordList: res.data, // 所有任务记录
                            othermarkers: list, // 除了当前定位以外的其他点
                            markers: list1, // 所有点
                            time: that.formatDate1(time1)
                        })
                        that.getInstance()
                    }
                })
            },
            getRandomNum() { // 获取sampleNums位随机数
                let that = this
                let randoms = [];
                //随机产生mix-max之间的一个数（避免首末概率不均，采用max+1，向下取整）
                function randomInteger(min, max) {
                    let rand = min + Math.random() * (max + 1 - min);
                    return Math.floor(rand);
                }
                while (true) {
                    //定义一个变量保存是否存在
                    var isExists = false;
                    // 获取一个1–100之间的数
                    var random = randomInteger(1, that.data.inventoryList.length)
                    console.log('-----random', random);
                    // 判断当前随机数是否已经存在
                    //通过randoms.length来确定要判断几次
                    for (let i = 0; i < randoms.length; i++) {
                        if (random === randoms[i]) {
                            isExists = true;
                            break;
                        }
                    }
                    console.log('-----randoms', randoms);
                    // 如果不存在，则添加进去
                    if (!isExists) {
                        randoms.push(random);
                        console.log('---adsf', randoms);
                    }
                    // 如果有10位随机数了，就跳出
                    console.log('---that.data.sampleNums', that.data.sampleNums);
                    if (randoms.length === parseInt(that.data.sampleNums)) {
                        console.log('---adsf', randoms);
                        break;
                    }
                }
                console.log('randoms', randoms)
                let list = []
                randoms.forEach(i => {
                    list.push(that.data.inventoryList[i-1])
                })
                console.log(that.data.inventoryList,'----list',list);
                return list;
            },
            getRandomPatrol() { // 生成随机巡查点
                let that = this
                let list = []
                G.get('/api/model/configuration').then(res => {
                    if (!res.errorMsg) {
                        res.forEach(p => {
                            if (p.id == '1643929472346492928') { // 获取类型
                                that.setData({
                                    sampleType: p.value
                                })
                            }
                            if (p.id == 'sampleScope') { // 获取范围
                                that.setData({
                                    sampleScope: p.value
                                })
                            }
                            if (p.id == 'sampleNums') { // 获取数量
                                that.setData({
                                    sampleNums: p.value
                                })
                            }
                        })
                        let type = that.data.sampleType==1?'hw_facility_toilet':that.data.sampleType==2?'hw_facility_septic_tank':'1'
                        G.get('/v1/facility?longitude=' + that.data.longitude + '&latitude=' + that.data.latitude + '&type=' + type + '&pageNum=1&pageSize=100').then(res => {
                            if (!res.errorMsg) {
                                let inventoryList1 = []
                                console.log('---that.data.sampleScope', that.data.sampleScope);
                                res.rows.forEach(r => {
                                    // console.log('---r.distance',r.distance);
                                    if (r.distance < that.data.sampleScope) {
                                        inventoryList1.push(r)
                                    }
                                })
                                console.log('----inventoryList1', inventoryList1);
                                that.setData({
                                    inventoryList: inventoryList1
                                })
                                if (inventoryList1.length > 0) {
                                    let allInv = []
                                    if (inventoryList1.length <= that.data.sampleNums) {
                                        // 所有点都显示
                                        console.log('显示所有点');
                                        allInv = inventoryList1
                                    } else {
                                        console.log('随机生成');
                                        allInv = that.getRandomNum()
                                    }
                                    for (let i = 0; i < allInv.length; i++) {
                                        let paramJson = {
                                            latitude: allInv[i].latitude,
                                            longitude: allInv[i].longitude,
                                            iconPath: G.Storage.get('APIURL') + '/file/1596477445610016768',
                                            width: '30',
                                            height: '30',
                                        }
                                        list.push(paramJson)
                                    }
                                    let list1 = []
                                    list1.push(...list)
                                    list1.push(...that.data.currenMarker)
                                    console.log('----list',list);
                                    console.log('----list1',list1);
                                    that.setData({
                                        recordList: allInv, // 所有任务记录
                                        othermarkers: list, // 除了当前定位以外的其他点
                                        markers: list1, // 所有点
                                        isZhiNeng: 1,
                                    })
                                    console.log('--recordList1', that.data.recordList);
                                    console.log('---markers4', that.data.markers);
                                    let time1 = new Date();
                                    G.Storage.set('isZhiNeng', {
                                        recordList: res.data, // 所有任务记录
                                        othermarkers: list, // 除了当前定位以外的其他点
                                        markers: list1, // 所有点
                                        time: that.formatDate1(time1)
                                    })
                                    that.getInstance() ///
                                    G.toask('推荐已显示!')
                                } else {
                                    console.log('附近没有资源点');
                                    G.toask('附近没有资源点!')
                                }

                                // for (let i = 0; i < res.rows.length; i++) {
                                //     let paramJson = {
                                //         latitude: res.data[i].location[1],
                                //         longitude: res.data[i].location[0],
                                //         iconPath: G.Storage.get('APIURL') + '/file/1596477445610016768',
                                //         width: '30',
                                //         height: '30',
                                //     }
                                //     list.push(paramJson)
                                // }
                                // let list1 = []
                                // list1.push(...list)
                                // list1.push(...that.data.currenMarker)
                                // that.setData({
                                //     recordList: res.data, // 所有任务记录
                                //     othermarkers: list, // 除了当前定位以外的其他点
                                //     markers: list1, // 所有点
                                //     isZhiNeng: 1,
                                // })
                                // console.log('--recordList1', that.data.recordList);
                                // console.log('--markers4', that.data.markers);
                                // let time1 = new Date(); 
                                // G.Storage.set('isZhiNeng', {
                                //     recordList: res.data, // 所有任务记录
                                //     othermarkers: list, // 除了当前定位以外的其他点
                                //     markers: list1, // 所有点
                                //     time: that.formatDate1(time1)
                                // })
                                // that.getInstance()
                            }
                        })
                    }
                })
            },
            // 格式化时间--时分
            formatDate(times) {
                var date = new Date(times);
                var year = date.getFullYear().toString(); //年份
                var month = (date.getMonth() + 1).toString(); //月份
                var day1 = date.getDate(); //日
                if (day1.toString().length == 1) {
                    var day = '0' + day1.toString()
                } else {
                    var day = day1.toString()
                }
                var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
                var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
                var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return hour + ':' + minute
                //   year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
            },
            // 格式化时间--年月日
            formatDate1(times) {
                var date = new Date(times);
                var year = date.getFullYear().toString(); //年份
                var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString() //月份
                // (date.getMonth() + 1).toString(); 
                var day1 = date.getDate(); //日
                if (day1.toString().length == 1) {
                    var day = '0' + day1.toString()
                } else {
                    var day = day1.toString()
                }
                var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
                var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
                var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return year + '-' + month + '-' + day
                //   year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
            },
            // 格式化时间--时分秒
            formatDate2(times) {
                var date = new Date(times);
                var year = date.getFullYear().toString(); //年份
                var month = (date.getMonth() + 1).toString(); //月份
                var day1 = date.getDate(); //日
                if (day1.toString().length == 1) {
                    var day = '0' + day1.toString()
                } else {
                    var day = day1.toString()
                }
                var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
                var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
                var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return hour + ':' + minute + ':' + second
                //   year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
            },
            // 获取实时时间（时分）显示在页面
            getCurrentTime() {
                let that = this
                let time1 = new Date();
                // console.log('----time1', time1);
                let time2 = that.formatDate(time1)
                // console.log('----time2', time2);
                that.setData({
                    currentTime: time2
                })
                // console.log('---currentTime', that.data.currentTime);
                if (that.data.timeController) {
                    setTimeout(() => {
                        that.getCurrentTime()
                    }, 1000)
                }
            },
            // 数组中删除空串
            solveNullArray(list) {
                let array2 = []
                for (let c = 0; c < list.length; c++) {
                    if (!list[c] == "") {
                        array2.push(list[c])
                    }
                }
                return array2
            },
            // 获取两个点之间的距离
            getDistance(lat1, lng1, lat2, lng2) {
                lat1 = lat1 || 0;
                lng1 = lng1 || 0;
                lat2 = lat2 || 0;
                lng2 = lng2 || 0;
                var rad1 = lat1 * Math.PI / 180.0;
                var rad2 = lat2 * Math.PI / 180.0;
                var a = rad1 - rad2;
                var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
                var r = 6378137;
                var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
                return distance;
            },
            // 计算当前位置距离每个打卡点的距离
            getInstance() {
                let that = this
                let list = that.data.othermarkers
                let list1 = [] // 每个点的距离
                for (let i = 0; i < list.length; i++) {
                    let num1 = Number(list[i].latitude);
                    let a1 = num1.toFixed(15);
                    let num2 = Number(list[i].longitude);
                    let a2 = num2.toFixed(15);
                    let num3 = Number(that.data.latitude);
                    let a3 = num3.toFixed(15);
                    let num4 = Number(that.data.longitude);
                    let a4 = num4.toFixed(15);
                    list1.push(that.getDistance(a1, a2, a3, a4))
                }
                console.log('---距离', list1);
                let num = 10000 //最小距离
                let index = 0
                for (let i = 0; i < list1.length; i++) {
                    if (num > list1[i]) {
                        num = list1[i]
                        index = i
                    }
                }
                console.log('--num', num, index);
                console.log('--最近的点信息', that.data.recordList[index]);
                that.setData({
                    minJuli: num,
                    index: index,
                })
                wx.hideLoading()
            },
            bindtapDaka(statu){
                if(this.data.patroltype != 3){
                    G.postWeRun().then(res => {
                        this.daka(statu)
                    })
                }else{
                    this.daka(statu)
                }
            },
            // 打卡
            daka(statu) {
                let that = this
                statu = statu == 3 ? 3 : 2
                if (statu == 2) {
                    let uploader = new G.Upload({
                        url: '/upload',
                        accept: 'image',
                        callback: ret => {
                            that.data.uploadImg = '/file/' + ret[0].id
                            if (that.data.minJuli < that.data.juli) {
                                console.log('---任务打卡');
                                that.dakaFunc1(that.data.index, statu)
                            } else {
                                console.log('---自由打卡');
                                that.dakaFunc(statu)
                            }
                        }
                    })
                    uploader.click()
                } else {
                    if (that.data.minJuli < that.data.juli) {
                        console.log('---任务打卡');
                        that.dakaFunc1(that.data.index, statu)
                    } else {
                        console.log('---自由打卡');
                        that.dakaFunc(statu)
                    }
                }
            },
            // 添加打卡记录-不在任务范围内，新增记录
            dakaFunc(statu) {
                let that = this
                let units = that.data.units
                statu = statu == 3 ? 3 : 2
                // if (units.length == 0) {
                //     console.log('--units2', units);
                //     // wx.showToast({
                //     //     title: '不在管理范围内',
                //     //     icon: 'error'
                //     // })
                // } else {
                that.freeDaka(statu)
                // }
            },
            // 自由打卡
            freeDaka(statu) {
                let that = this
                statu = statu == 3 ? 3 : 2
                let param = {}
                param.userId = G.Storage.get('userInfo').id
                let time1 = new Date()
                param.patrolDate = that.formatDate1(time1)
                param.latitude = that.data.latitude
                param.longitude = that.data.longitude
                param.local = that.data.address
                param.statu = statu
                param.patroltype = that.data.patroltype
                param.inventoryId = that.data.inventoryId
                param.caseId = that.data.caseId
                param.koufenId = that.data.koufenId
                param.unityId = that.data.unitId
                param.unityName = that.data.unitName
                param.enterpriceId = G.Storage.get('userInfo').enterpriceId
                param.enterpriceName = G.Storage.get('userInfo').enterpriceName
                param.img = that.data.uploadImg
                console.log('---param', param);
                G.post('/api/model/g_patrol_record', param).then(res => {
                    if (!res.errorMsg) {
                        G.addClock(that.data).then(res => {
                            G.toask('巡查成功').then(() => {
                                wx.navigateBack()
                            })
                        })
                    } else {
                        wx.showToast({
                            title: res.errorMsg,
                            icon: 'error'
                        })
                    }
                })
            },
            // 添加打卡记录-在任务范围内，修改记录
            dakaFunc1(index, statu) {
                console.log('---statu', index, statu);
                let that = this
                statu = statu == 3 ? 3 : 2
                console.log('---a', that.data.recordList);
                console.log('--markers3', that.data.markers);
                if (that.data.recordList.length == 0) {
                    that.freeDaka() // 没有任务就自由打卡
                } else {
                    if (that.data.isZhiNeng == 1) {
                        console.log('freeDaka');
                        that.freeDaka()
                    } else {
                        if (that.data.recordList[index].statu != 1) {
                            console.log('已打卡', that.data.caseId, that.data.koufenId);
                            wx.showToast({
                                title: '已打卡',
                                icon: 'error'
                            })
                        } else {
                            let units = that.data.units
                            // if (units.length == 0) {
                            //     console.log('--units3', units);
                            //     // wx.showToast({
                            //     //     title: '不在管理范围内',
                            //     //     icon: 'error'
                            //     // })
                            // } else {
                            let param = that.data.recordList[index]
                            G.put('/api/model/g_patrol_record', {
                                unityId: that.data.unitId,
                                unityName: that.data.unitName,
                                id: param.id,
                                statu: statu,
                                inventoryId: that.data.inventoryId,
                                caseId: that.data.caseId,
                                koufenId: that.data.koufenId,
                                img: that.data.uploadImg,
                                enterpriceId: G.Storage.get('userInfo').enterpriceId,
                                enterpriceName: G.Storage.get('userInfo').enterpriceName
                            }).then(res => {
                                if (!res.errorMsg) {
                                    G.get(G.Storage.get('JAVAURL') + '/sample/subtractWeight', {
                                        id: that.data.inventoryId
                                    }).then(res => {
                                        console.log('--res', res);
                                    })
                                    G.put('/api/model/g_patrol_task', {
                                        id: param.taskId,
                                        isOnline: 2,
                                    }).then(res1 => {
                                        if (!res1.errorMsg) {
                                            G.addClock(that.data).then(res => {
                                                G.toask('打卡成功').then(() => {
                                                    wx.navigateBack()
                                                    that.getPatrolTask()
                                                })
                                            })
                                        }
                                    })
                                }
                            })
                            // }
                        }
                    }
                }
            },
            // 选择资源
            selectInventory(e) {
                let that = this
                that.setData({
                    nameIndex: e.detail.value,
                    unit: that.data.units[parseInt(e.detail.value)],
                    name: that.data.units[parseInt(e.detail.value)].name,
                    address: that.data.units[parseInt(e.detail.value)].address,
                    inventoryId: that.data.units[parseInt(e.detail.value)].id,
                })
                console.log(this.data.firstType);
            },
            getUserName() {
                let time1 = new Date()
                console.log('---nowTime', parseInt(time1.getTime() / 1000));
                let uesrId = G.Storage.get('userInfo').id
                let that = this
                G.get('/api/model/user', {
                    id: uesrId
                }).then(res => {
                    console.log('---userInfo', res);
                    if (!res.errorMsg) {
                        console.log('---res.userName', res.userName);
                        that.setData({
                            userId1: res.userName
                        })
                        console.log('---userId', that.data.userId1);
                    }
                })
            },


            onShow(e) {
                this.setData({
                    timeController: true
                })
                this.getCurrentTime()
            },
            onHide() {
                this.setData({
                    timeController: false
                })
            },
            setGrid() { //提示设置常用网格
                let setMineGrided = G.Storage.get('setMineGrided', 1)
                if (!setMineGrided && this.data.patroltype == 1) {
                    G.confirm('请设置常用巡查网格').then(() => {
                        G.Storage.set('setMineGrided', 1)
                        G.$go('/pages/grid/mine')
                    })
                }
            }
        },
        mounted(opitions) {
            console.log('---opitions', opitions);
            if (opitions.type == 'day') {
                this.setData({
                    patroltype: 1
                })
            } else if (opitions.type == 'month') {
                this.setData({
                    patroltype: 2
                })
            } else if (opitions.type == 'safe') {
                this.setData({
                    patroltype: 3
                })
            }
            this.getlocal()
            this.getCurrentTime()
            this.setGrid()
            // this.getUserName()
        }
    })
})(wx.$)